<?php
namespace app\controller;

use app\BaseController;

use think\facade\Db;
use think\facade\Request;
use think\captcha\facade\Captcha;
use think\cache\driver\Redis;
use think\facade\Cache;

/**
* 自动执行脚本接口
* 20210720
*/
class Timing extends BaseController
{
	protected $userInfo;
	protected $request;
	public function __construct(Request $request){
        $this->request = $request;
	}
	/**
	*计算是否要给用户分红
	*/
	public function user(){
	    echo 11111111111;exit;
		$redis = new Redis();
        $redis->handler()->select(10);
		$config = $redis->get("yt_activity");
		$config = json_decode($config,true);
		$act = Db::table("t_purchase")->where("status",2)->where("id",">=","3")->order("id desc")->find();
		if($act){
			$id = $act['id'] - 2;
			Db::startTrans();
			try {
				$list = Db::table("t_purchase_user")->where("p_id",$id)->where("type",0)->select()->toArray();
				foreach ($list as $k => $v) {
					$available_balance = $v['number'] + $v['number']*$config['user'];
					//修改用户总资产 -- 当前投资用户的
					Db::table("t_user_coin")->where("user_id",$v['user_id'])->inc("available_balance",$available_balance)->update();
					$dataArray = array(
						"p_id"=>$id,
						"user_id"=>$v['user_id'],
						"principal"=>$v['number'],
						"reward"=>$available_balance,
						'ctime'=>date("Y-m-d H:i:s")
					);
					//新增一条用户奖励记录
					Db::table("t_purchase_personal")->insert($dataArray);
					$bill=array(
						'user_id'=>$v['user_id'],
						'coin_name'=>'USDT',
						'sub_type'=>0,
						'reason'=>'ShareOut',
						'change_amount'=>$available_balance,
						'comment'=>'蟻團獎勵，期數：'.$id,
						'last_time'=>date("Y-m-d H:i:s")
					);
					//新增一条用户资产变动记录
					Db::table("t_user_bill")->insert($bill);
					//修改当前用户投资分红状态
					Db::table("t_purchase_user")->where("id",$v['id'])->update(['type'=>1]);
					$referrer = Db::table("t_user")->where("id",$v['user_id'])->value("referrer");
					if($referrer != 0){
						if(Db::table("t_purchase_user")->where("p_id",$id)->where("user_id",$referrer)->find()){
							//新增一条推荐奖励记录
							Db::table("t_purchase_recommend")->insert(array("p_id"=>$id,"user_id"=>$referrer,"rec_uid"=>$v['user_id'],"money"=>$v['number'],"amount"=>$v['number']*$config['recommend'],'ctime'=>date("Y-m-d H:i:s")));
							//修改推荐用户资产信息
							Db::table("t_user_coin")->where("user_id",$referrer)->inc("available_balance",$v['number']*$config['recommend'])->update();
							$bill2=array(
								'user_id'=>$referrer,
								'coin_name'=>'USDT',
								'sub_type'=>0,
								'reason'=>'Referrer',
								'change_amount'=>$v['number']*$config['recommend'],
								'comment'=>'蟻團推薦獎勵，期數：'.$id,
								'last_time'=>date("Y-m-d H:i:s")
							);
							//新增一条用户资产变动记录 -- 获取推荐奖励
							Db::table("t_user_bill")->insert($bill2);
						}
					}
				}
				Db::commit();
			}catch (\Exception $e) {
			    // 回滚事务
			    Db::rollback();
			}	
		}
	}

	/**
	*	是否要新增活动
	*/
	public function add_act(){
		$redis = new Redis();
		$config = $redis->get("yt_activity");
		$config = json_decode($config,true);
		$act = Db::table("t_purchase")->order("id desc")->find();
		if($act['status'] == 2){
			$purchase = array(
				"coin_name"=>'USDT',
				"start_time"=>date("Y-m-d H:i:00",time()+$config['next']*60*60),
				"end_time"=>date("Y-m-d H:i:00",time()+$config['next']*60*60+86400),
				"delay"=>0,
				"quantity"=>$act['quantity'] + ceil($act['quantity']*$config['increase']),
				"sign_number"=>0,
				"price"=>$config['money'],
				"amount"=>0,
				"ctime"=>date("Y-m-d H:i:s"),
				"status"=>0
			);
			Db::table("t_purchase")->insert($purchase);
		}elseif($act['status'] == 1){
			if($act['quantity']*$act['price'] == $act['amount']){
				$purchase = array(
					"coin_name"=>'USDT',
					"start_time"=>date("Y-m-d H:i:00",time()+$config['next']*60*60),
					"end_time"=>date("Y-m-d H:i:00",time()+$config['next']*60*60+86400),
					"delay"=>0,
					"quantity"=>$act['quantity'] + ceil($act['quantity']*$config['increase']),
					"sign_number"=>0,
					"price"=>$config['money'],
					"amount"=>0,
					"ctime"=>date("Y-m-d H:i:s"),
					"status"=>0
				);
				Db::table("t_purchase")->insert($purchase);
				Db::table("t_purchase")->where("id",$act['id'])->update(['status'=>2]);
			}else{	
				if($act['quantity']*$act['price'] > $act['amount'] && strtotime($act['end_time'])+$act['delay'] < time()){
				    echo 5555;
					Db::table("t_purchase")->where("id",$act['id'])->update(['status'=>3]);
				}
			}
		}
	}

	/**
	*	是否需要退回投资
	*/
	public function end_act(){
        $data = Db::table("t_purchase")->where("status",3)->where("id",">",3)->order("id desc")->find();
        if($data){
            $id = $data['id'] - 2;
            $list = Db::table("t_purchase_user")->where("p_id",'>',$id)->where('type',0)->select()->toArray();
			Db::startTrans();
			try {
			    if($list){
                    foreach ($list as $k=>$v){
                        $bill=array(
    						'user_id'=>$v['user_id'],
    						'coin_name'=>'USDT',
    						'sub_type'=>0,
    						'reason'=>'FundCc',
    						'change_amount'=>$v['number'],
    						'comment'=>'蟻團活動失敗，返回用戶投資，投資ID：'.$v['p_id'],
    						'last_time'=>date("Y-m-d H:i:s")
    					);
    					//新增一条用户资产变动记录
    					Db::table("t_user_bill")->insert($bill);
    					Db::table("t_user_coin")->where("user_id",$v['user_id'])->inc("available_balance",$v['number'])->update();
    					Db::table("t_purchase_user")->where("id",$v['id'])->update(['type'=>2]);
                    }
                }
				Db::commit();
			}catch (\Exception $e) {
			    // 回滚事务
			    Db::rollback();
			}
                
        }
	}

	/**
	*	发放大奖
	*/
	public function grand_prix(){
        $data = Db::table("t_purchase")->where("status",3)->find();
        if($data){
            $amount1 = Db::table("t_purchase_big_reward")->where("status",0)->sum('amount');
            $amount2 = Db::table("t_purchase_retained")->order("id desc")->value("money");
            $money = ($amount1+$amount2) * 0.2;
            $amount = ($amount1+$amount2)*0.8/20;
            $list = Db::table("t_purchase_user_details".$data['id'])->order("id desc")->limit(20)->select()->toArray();
            Db::startTrans();
			try {
			    if($list){
                    foreach ($list as $k=>$v){
                        $dataArray = array(
                            "user_id"=>$v['user_id'],
                            "money"=>$amount,
                            "ctime"=>date("Y-m-d H:i:s"),
                            "haoma"=>$v['id'],
                            "p_id"=>$data['id'],
                        );
    					//新增一条大奖记录
    					Db::table("t_purchase_big")->insert($dataArray);
                        $bill=array(
    						'user_id'=>$v['user_id'],
    						'coin_name'=>'USDT',
    						'sub_type'=>0,
    						'reason'=>'ShareOut',
    						'change_amount'=>$amount,
    						'comment'=>'蟻團大獎獎勵，獎勵獲取期數：'.$data['id'],
    						'last_time'=>date("Y-m-d H:i:s")
    					);
    					//新增一条用户资产变动记录
    					Db::table("t_user_bill")->insert($bill);
    					Db::table("t_user_coin")->where("user_id",$v['user_id'])->inc("available_balance",$amount)->update();
                    }
                    $id = $data['id'] - 2;
                    Db::table("t_purchase_user")->where("p_id",$id)->update(['type'=>3]);
                    Db::table("t_purchase_big_reward")->where("p_id",'<=',$id)->update(['status'=>1]);
    				Db::table("t_purchase_retained")->insert(array("money"=>$money,"qishu"=>1,"ctime"=>date("Y-m-d H:i:s")));
                }
				Db::commit();
			}catch (\Exception $e) {
			    // 回滚事务
			    Db::rollback();
			}
        }
	}
	
	/*
	 *修改活动开始状态 
	 *
	*/
	public function start_act(){
	    //活动到开始时间了 修改活动状态
	    $data = Db::table("t_purchase")->where("status",0)->order("id desc")->find();
	    if($data){
	        if(strtotime($data['start_time']) <= time()){
	            Db::table("t_purchase")->where("id",$data['id'])->update(['status'=>1]);
	            echo '活動開始成功'.$data['id'];
	        }else{
	            echo '不到活動開始時間';
	        }
	    }else{
            echo '沒有未開始活動';
        }
	}
	
	public function big(){
	    $redis = new Redis();
        $redis->handler()->select(10);
		$config = $redis->get("yt_activity");
		$config = json_decode($config,true);
		$act = Db::table("t_purchase")->where("status",2)->where("id",">=","3")->order("id desc")->find();
		if($act){
			$id = $act['id'] - 2;
			$amount = Db::table("t_purchase")->where("id",$id)->value("amount");
			if(Db::table("t_purchase_big_reward")->where("p_id",$id)->find()){
			    
			}else{
			    Db::table("t_purchase_big_reward")->insert(
        		    array(
        		        'p_id'=>$id,
        		        'money'=>$amount,
        		        'amount'=>$amount*$config['jackpot'],
        		        'status'=>0,
        		        'ctime'=>date("Y-m-d H:i:s")
        		    )
        		);
			}	
		}
	}
	
	public function team(){
	    $redis = new Redis();
        $redis->handler()->select(10);
		$config = $redis->get("yt_activity");
		$config = json_decode($config,true);
		$act = Db::table("t_purchase")->where("status",2)->where("id",">=","3")->order("id desc")->find();
		if($act){
			$id = $act['id'] - 2;
			$amount = Db::table("t_purchase")->where("id",$id)->value("amount");
			if(Db::table("t_purchase_team")->where("p_id",$id)->find()){
			    
			}else{
			    Db::table("t_purchase_team")->insert(
        		    array(
        		        "p_id"=>$id,
        		        'money'=>$amount*$config['team'],
        		        'ctime'=>date("Y-m-d H:i:s")
        		    )
        		 );
			}	
		}
        		
	}
	
	public function  act_return(){
	    $list = Db::table("t_purchase")->where("status",3)->where("id",3)->find();
	    if($list){
	        $data = Db::table("t_purchase_user")->where("type",0)->select()->toArray();
	        if($data){
	            foreach ($data as $k => $v){
	                $bill=array(
						'user_id'=>$v['user_id'],
						'coin_name'=>'USDT',
						'sub_type'=>0,
						'reason'=>'FundCc',
						'change_amount'=>$v['number'],
						'comment'=>'蟻團未完成退回奖励：'.$v['p_id'],
						'last_time'=>date("Y-m-d H:i:s")
					);
					//新增一条用户资产变动记录
					Db::table("t_user_bill")->insert($bill);
					Db::table("t_user_coin")->where("user_id",$v['user_id'])->inc("available_balance",$v['number'])->update();
					Db::table("t_purchase_user")->where("id",$v['id'])->update(['type'=>2]);
	            }
	        }else{
	            echo 11111;
	        }
	        
	        Db::table("t_purchase")->update(['status'=>4]);
	    }else{
	        echo 1234;
	    }
	    
	}
}